package com.byxy.shop.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.byxy.shop.service.GoodsSearchService;
import com.byxy.ssm.shop.vo.GoodsDetailVO;
import com.byxy.ssm.shop.vo.SearchPageCategoryVO;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class SearchController {

	@Value("${page.rows}")
	private Integer rows;

	@Autowired
	private GoodsSearchService goodsSearchService;

	@GetMapping("search")
	public String search(Integer goodsCategoryId, String keyword,Integer page,String orderBy, Model model) {
		log.info("rows=" + rows);
		Map<String, Object> pageResult = new HashMap<>();
		
		int currPage = 1;
		if(page != null) {
			page = currPage;
		}
		List<GoodsDetailVO> list = goodsSearchService.findByCategoryIdAndKeyword(goodsCategoryId, keyword, currPage, rows,orderBy);

		int total = goodsSearchService.getTotalByCategoryIdAndKeyword(goodsCategoryId, keyword);
		int totalPage = (total + rows - 1) / rows;
		pageResult.put("list", list);
		pageResult.put("currPage", currPage);
		pageResult.put("totalPage", totalPage);
		
		SearchPageCategoryVO searchPageCategoryVO = goodsSearchService.getSearchPageCategoryVO(goodsCategoryId); // new SearchPageCategoryVO();
		model.addAttribute("pageResult", pageResult);
		model.addAttribute("searchPageCategoryVO", searchPageCategoryVO);
		// 回传
		model.addAttribute("goodsCategoryId", goodsCategoryId);
		log.info("==goodsCategoryId======" + goodsCategoryId);
		log.info("==keyword======" + keyword);
		return "mall/search";
	}
}
